{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true,
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "# 4 Pandas的索引操作"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-05-01T03:18:23.664883Z",
     "start_time": "2024-05-01T03:18:23.207612200Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   A          B    C  D       E        F\n",
      "0  1 2019-09-26  1.0  1  Python  wangdao\n",
      "1  1 2019-09-26  1.0  2    Java  wangdao\n",
      "2  1 2019-09-26  1.0  3     C++  wangdao\n",
      "3  1 2019-09-26  1.0  4       C  wangdao\n",
      "--------------------------------------------------\n",
      "   A          B    C  D       E        F\n",
      "0  1 2019-09-26  1.0  1  Python  wangdao\n",
      "1  1 2019-09-26  1.0  2    Java  wangdao\n",
      "--------------------------------------------------\n",
      "Index([0, 1, 2, 3], dtype='int64')\n"
     ]
    }
   ],
   "source": [
    "dict_data = {'A': 1,\n",
    "             'B': pd.Timestamp('20190926'),\n",
    "             'C': pd.Series(1, index=list(range(4)),dtype='float32'),\n",
    "             'D': np.array([1,2,3,4],dtype='int32'),\n",
    "             'E': [\"Python\",\"Java\",\"C++\",\"C\"],\n",
    "             'F': 'wangdao' }\n",
    "df_obj2 = pd.DataFrame(dict_data)\n",
    "print(df_obj2)\n",
    "print('-'*50)\n",
    "\n",
    "print(df_obj2.loc[0:1])\n",
    "print('-'*50)\n",
    "\n",
    "print(df_obj2.index)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2024-05-01T03:18:23.758028300Z",
     "start_time": "2024-05-01T03:18:23.666523300Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "outputs": [],
   "source": [
    "# 索引对象的值不可变（上面代码增加）\n",
    "# df_obj2.index[0] = 2"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2024-05-01T03:18:23.772987700Z",
     "start_time": "2024-05-01T03:18:23.694803500Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "3 常见的Index种类\n",
    "•Index，索引  可以是各种类型\n",
    "•Int64Index，整数索引\n",
    "•MultiIndex，层级索引，难度较大\n",
    "•DatetimeIndex，时间戳类型"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    0\n",
      "b    1\n",
      "c    2\n",
      "d    3\n",
      "e    4\n",
      "dtype: int64\n",
      "Index(['a', 'b', 'c', 'd', 'e'], dtype='object')\n"
     ]
    }
   ],
   "source": [
    "ser_obj = pd.Series(range(5), index = list(\"abcde\"))\n",
    "print(ser_obj)\n",
    "print(ser_obj.index)"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2024-05-01T03:19:29.145109700Z",
     "start_time": "2024-05-01T03:19:29.125365900Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n"
     ]
    }
   ],
   "source": [
    "# 行索引，不仅可以用索引名，可以用索引位置或来取\n",
    "print(ser_obj['b']) #索引名\n",
    "print(ser_obj[2]) #索引位置"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2024-05-01T03:18:23.773985600Z",
     "start_time": "2024-05-01T03:18:23.746060500Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b    1\n",
      "c    2\n",
      "dtype: int64\n",
      "b    1\n",
      "c    2\n",
      "d    3\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "# 切片索引\n",
    "print(ser_obj[1:3])  #索引位置取数据，左闭右开\n",
    "print(ser_obj['b':'d'])  #索引名  左闭右闭"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2024-05-01T03:18:23.773985600Z",
     "start_time": "2024-05-01T03:18:23.758028300Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    0\n",
      "c    2\n",
      "e    4\n",
      "dtype: int64\n",
      "a    0\n",
      "e    4\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "# 不连续索引\n",
    "print(ser_obj[[0, 2, 4]])\n",
    "print(ser_obj[['a', 'e']])"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2024-05-01T03:18:23.861750200Z",
     "start_time": "2024-05-01T03:18:23.772987700Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    False\n",
      "b    False\n",
      "c    False\n",
      "d     True\n",
      "e     True\n",
      "dtype: bool\n",
      "--------------------------------------------------\n",
      "d    3\n",
      "e    4\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "# 布尔索引\n",
    "ser_bool = ser_obj > 2\n",
    "print(ser_bool)\n",
    "print('-'*50)\n",
    "\n",
    "# print(ser_obj[ser_bool])\n",
    "print(ser_obj[ser_obj > 2]) #取出大于2的元素"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2024-05-01T03:43:53.086751100Z",
     "start_time": "2024-05-01T03:43:53.065792Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 4.4 DataFrame索引"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "          a         b         c         d\n",
      "0  0.496714 -0.138264  0.647689  1.523030\n",
      "1 -0.234153 -0.234137  1.579213  0.767435\n",
      "2 -0.469474  0.542560 -0.463418 -0.465730\n",
      "3  0.241962 -1.913280 -1.724918 -0.562288\n",
      "4 -1.012831  0.314247 -0.908024 -1.412304\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "\n",
    "np.random.seed(42)\n",
    "df_obj = pd.DataFrame(np.random.randn(5,4),\n",
    "                      columns = ['a', 'b', 'c', 'd'])\n",
    "print(df_obj.head())"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2024-05-01T04:22:02.342181Z",
     "start_time": "2024-05-01T04:22:02.312055500Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0    0.496714\n",
      "1   -0.234153\n",
      "2   -0.469474\n",
      "3    0.241962\n",
      "4   -1.012831\n",
      "Name: a, dtype: float64\n",
      "--------------------------------------------------\n",
      "          a\n",
      "0  0.496714\n",
      "1 -0.234153\n",
      "2 -0.469474\n",
      "3  0.241962\n",
      "4 -1.012831\n",
      "<class 'pandas.core.frame.DataFrame'>\n",
      "--------------------------------------------------\n",
      "          a         b         c\n",
      "0  0.496714 -0.138264  0.647689\n",
      "1 -0.234153 -0.234137  1.579213\n",
      "--------------------------------------------------\n",
      "          a         c\n",
      "0  0.496714  0.647689\n",
      "1 -0.234153  1.579213\n",
      "2 -0.469474 -0.463418\n",
      "3  0.241962 -1.724918\n",
      "4 -1.012831 -0.908024\n",
      "<class 'pandas.core.frame.DataFrame'>\n"
     ]
    }
   ],
   "source": [
    "# 列索引\n",
    "print(df_obj['a']) # 返回Series类型\n",
    "print('-'*50)\n",
    "\n",
    "print(df_obj[['a']]) # 返回DataFrame类型\n",
    "print(type(df_obj[['a']]))\n",
    "print('-'*50)\n",
    "\n",
    "print(df_obj[['a','c']]) # 返回DataFrame类型\n",
    "print(type(df_obj[['a','c']]))"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2024-05-01T04:23:26.584683300Z",
     "start_time": "2024-05-01T04:23:26.542795700Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    0\n",
      "b    1\n",
      "c    2\n",
      "d    3\n",
      "e    4\n",
      "dtype: int64\n",
      "--------------------------------------------------\n",
      "b    1\n",
      "c    2\n",
      "d    3\n",
      "dtype: int64\n",
      "--------------------------------------------------\n",
      "b    1\n",
      "c    2\n",
      "d    3\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "# 标签索引 loc，建议使用loc，效率更高\n",
    "# Series\n",
    "print(ser_obj)\n",
    "print('-'*50)\n",
    "\n",
    "print(ser_obj['b':'d'])\n",
    "print('-'*50)\n",
    "\n",
    "\n",
    "print(ser_obj.loc['b':'d']) #前闭后闭\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2024-05-01T03:18:23.881711900Z",
     "start_time": "2024-05-01T03:18:23.836819900Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "          a         b         c         d\n",
      "a  1.465649 -0.225776  0.067528 -1.424748\n",
      "b -0.544383  0.110923 -1.150994  0.375698\n",
      "c -0.600639 -0.291694 -0.601707  1.852278\n",
      "d -0.013497 -1.057711  0.822545 -1.220844\n",
      "e  0.208864 -1.959670 -1.328186  0.196861\n",
      "--------------------------------------------------\n",
      "a    1.465649\n",
      "b   -0.544383\n",
      "c   -0.600639\n",
      "d   -0.013497\n",
      "e    0.208864\n",
      "Name: a, dtype: float64\n",
      "--------------------------------------------------\n",
      "a    1.465649\n",
      "b   -0.225776\n",
      "c    0.067528\n",
      "d   -1.424748\n",
      "Name: a, dtype: float64\n",
      "--------------------------------------------------\n",
      "          b         c         d\n",
      "a -0.225776  0.067528 -1.424748\n",
      "b  0.110923 -1.150994  0.375698\n",
      "c -0.291694 -0.601707  1.852278\n",
      "          b         d\n",
      "a -0.225776 -1.424748\n",
      "c -0.291694  1.852278\n",
      "          b\n",
      "c -0.291694\n",
      "-0.2916937497932768\n"
     ]
    }
   ],
   "source": [
    "# DataFrame\n",
    "df_obj = pd.DataFrame(np.random.randn(5,4),\n",
    "                      columns = list('abcd'),\n",
    "                      index=list('abcde'))\n",
    "print(df_obj)\n",
    "print('-'*50)\n",
    "\n",
    "print(df_obj['a'])  #建议不用,拿的是列\n",
    "print('-'*50)\n",
    "\n",
    "print(df_obj.loc['a'])  #拿的是行\n",
    "print('-'*50)\n",
    "\n",
    "\n",
    "# 第一个参数索引行，第二个参数是列,loc或者iloc效率高于直接用取下标的方式，前闭后闭\n",
    "print(df_obj.loc['a':'c', 'b':'d']) #连续索引\n",
    "print(df_obj.loc[['a','c'], ['b','d']]) #不连续索引\n",
    "print(df_obj.loc[['c'],['b']]) #取一个值,返回的是DataFrame类型\n",
    "print(df_obj.loc['c','b'])  #取一个值"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-05-01T04:23:51.278035900Z",
     "start_time": "2024-05-01T04:23:51.233083700Z"
    }
   }
  },
  {
   "cell_type": "markdown",
   "source": [
    "## iloc 位置索引(推荐使用)"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    0\n",
      "b    1\n",
      "c    2\n",
      "d    3\n",
      "e    4\n",
      "dtype: int64\n",
      "--------------------------------------------------\n",
      "b    1\n",
      "c    2\n",
      "dtype: int64\n",
      "--------------------------------------------------\n",
      "b    1\n",
      "c    2\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "# Series\n",
    "print(ser_obj)\n",
    "print('-'*50)\n",
    "\n",
    "print(ser_obj[1:3])\n",
    "print('-'*50)\n",
    "\n",
    "print(ser_obj.iloc[1:3]) # 前闭后开[)，效率高\n"
   ],
   "metadata": {
    "collapsed": false,
    "pycharm": {
     "name": "#%%\n"
    },
    "ExecuteTime": {
     "end_time": "2024-05-01T04:28:50.156578600Z",
     "start_time": "2024-05-01T04:28:50.134637700Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "          a         b         c         d\n",
      "a  1.465649 -0.225776  0.067528 -1.424748\n",
      "b -0.544383  0.110923 -1.150994  0.375698\n",
      "c -0.600639 -0.291694 -0.601707  1.852278\n",
      "d -0.013497 -1.057711  0.822545 -1.220844\n",
      "e  0.208864 -1.959670 -1.328186  0.196861\n",
      "--------------------------------------------------\n",
      "          a         b\n",
      "a  1.465649 -0.225776\n",
      "b -0.544383  0.110923\n",
      "--------------------------------------------------\n",
      "          a         c\n",
      "a  1.465649  0.067528\n",
      "c -0.600639 -0.601707\n",
      "--------------------------------------------------\n",
      "1.465648768921554\n"
     ]
    }
   ],
   "source": [
    "# DataFrame，iloc是前闭后开[)\n",
    "print(df_obj)\n",
    "print('-'*50)\n",
    "\n",
    "print(df_obj.iloc[0:2, 0:2]) # 注意和df_obj.loc[0:2, 'a']的区别\n",
    "print('-'*50)\n",
    "\n",
    "print(df_obj.iloc[[0,2], [0,2]]) # 不连续索引\n",
    "print('-'*50)\n",
    "\n",
    "print(df_obj.iloc[0,0]) # 取一个值"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-05-01T04:28:58.834334800Z",
     "start_time": "2024-05-01T04:28:58.804574800Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "          0         1         2         3\n",
      "0 -0.479174 -0.185659 -1.106335 -1.196207\n",
      "1  0.812526  1.356240 -0.072010  1.003533\n",
      "2  0.361636 -0.645120  0.361396  1.538037\n",
      "3 -0.035826  1.564644 -2.619745  0.821903\n",
      "4  0.087047 -0.299007  0.091761 -1.987569\n",
      "--------------------------------------------------\n",
      "          0         1         2         3\n",
      "0 -0.479174 -0.185659 -1.106335 -1.196207\n",
      "1  0.812526  1.356240 -0.072010  1.003533\n",
      "--------------------------------------------------\n",
      "          0         1         2         3\n",
      "0 -0.479174 -0.185659 -1.106335 -1.196207\n",
      "1  0.812526  1.356240 -0.072010  1.003533\n",
      "2  0.361636 -0.645120  0.361396  1.538037\n"
     ]
    }
   ],
   "source": [
    "#没有设置行和列索引的DataFrame，iloc和loc的区别\n",
    "df_obj2 = pd.DataFrame(np.random.randn(5,4))\n",
    "print(df_obj2)\n",
    "print('-'*50)\n",
    "\n",
    "print(df_obj2.iloc[0:2]) #左闭右开\n",
    "print('-'*50)\n",
    "\n",
    "print(df_obj2.loc[0:2]) #左闭右闭"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-05-01T04:29:37.350477400Z",
     "start_time": "2024-05-01T04:29:37.308043200Z"
    }
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
